package team.first.movieapiv2pro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import team.first.movieapiv2pro.dao.GenreDAO;
import team.first.movieapiv2pro.domain.Genre;
import team.first.movieapiv2pro.service.GenreService;

import java.time.Duration;
import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2pro.service.impl
 * @Date: 2021/12/26 10:16
 * @Description:
 */
@Service
public class GenreServiceImpl implements GenreService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    GenreDAO genreDAO;

    @Override
    public List<Genre> list() {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String genres = operations.get("movie-api-v2:data:genres");

        List<Genre> genreList;

        if (genres != null) {
            genreList = JSON.parseArray(genres, Genre.class);
        } else {
            List<DBObject> dbObjects = genreDAO.selectAll();
            genreList = BeanUtil.copyToList(dbObjects, Genre.class);
            // 对结果进行缓存, 因为不会怎么变，所以设置60分钟
            stringRedisTemplate.opsForValue().set("movie-api-v2:data:genres", JSON.toJSONString(genreList), Duration.ofSeconds(60 * 60));
        }
        return genreList;
    }
}
